import CountDown from 'fe-countdown/dist/countdown.js';
import api from '../api';
import * as types from './types';
import BusFn from './../business/bus-fn';
import Order from './../business/order';
import checkOrder from "../business/check-order";
import {
  OrderList
}
from '../config';

export const test = ({
  dispatch, router
}) => {
  dispatch(types.TEST, 123, 12)
}

export const changeToastMsg = ({
  dispatch
}, content, type = 'error') => {
  dispatch(types.CHANGE_TOSAT_MSG, {
    content: content,
    type: type
  })
}


export const ordering = (store, data) => {
  data.orderNo = data.id;

  // store.dispatch(types.CHANGE_TOSAT_MSG, true, "正在下单", "cancel");

}


export const wechatPay = (store, data) => {
  let payargs;
  store.dispatch(types.CHANGE_MPGDIALOG_OPTS, {
    show: false
  })

  store.dispatch(types.SHOW_LOADING_MSG, "正在支付");
  api.checkoutOfFastOrder(data).then(response => {
    let result = response.data;
    if (result.code == 200) {
      const orderId = result.data.id;
      BusFn.completeOrder(data, result.data);
      api.orderPayWechat(data).then(
        response => {
          store.dispatch(types.HIDE_TOSAT_MSG);
          store.dispatch(types.HIDE_LOADING_MSG);
          if (response.data.code != 200) {
            return alert(response.data.msg);
          } else {
            payargs = response.data.parameters;
          }
          WeixinJSBridge.invoke('getBrandWCPayRequest', payargs,
            function(
              res) {
              console.log(payargs, res);
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                // if (true) { //debug
                //   if (true) { //debug
                //支付成功
                //加入初始化的detail
                let processStatus = data.processStatus;
                processStatus.addDetailOrdered();


                //倒计时
                var now = Date.now();
                var x = new CountDown({
                  endTime: now + 60 * 1000,
                  now: now,
                  fixNowDate: false,
                  render: function(outstring) {
                    processStatus.setCountDown(outstring +
                      "s");
                  },
                  template: '{{s}}',
                  delayTime: 1000
                })


                store.router.replace({
                  name: "order-detail"
                })

                // const _store = store,_order=data;
                checkOrder(OrderList.refundExpiration / 1000,
                    data.id)
                  .then(function(v) {
                    processStatus.addDetailReceived();
                    x.destory();
                    BusFn.completeOrder(data, v);
                  })
                  .catch(function(e) {
                    x.destory();
                    processStatus.addDetailFail();
                  })
              } else {
                // alert("支付失败，请重试");
                //先这样解决 todo
                return store.dispatch(types.CHANGE_MPGDIALOG_OPTS, {
                  iconType: "warn",
                  content: "支付失败",
                  btnContent: "重新下单",
                  btnFn: function() {
                    changeMpjDialogOptions(store, {
                      show: false
                    })
                    const orderItem = JSON.parse(JSON.stringify(
                      data))
                    data.emptyOrder();
                    data.setNewOrder(orderItem);
                    return store.router.replace("/");
                  },
                  show: true
                })

              }
            }
          ); //debug
          // if (typeof WeixinJSBridge == "undefined") {
          //   if (document.addEventListener) {
          //     document.addEventListener('WeixinJSBridgeReady',
          //       onBridgeReady,
          //       false);
          //   } else if (document.attachEvent) {
          //     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          //     document.attachEvent('onWeixinJSBridgeReady',
          //       onBridgeReady);
          //   }
          // } else {
          //   onBridgeReady();
          // }
        },
        response => {
          store.dispatch(types.HIDE_LOADING_MSG);
          store.dispatch(types.CHANGE_MPGDIALOG_OPTS, {
            iconType: "warn",
            content: "支付失败",
            btnContent: "重新支付",
            btnFn: function() {
              wechatPay(store, data)
            },
            show: true
          })
          console.log(response)
        });
    } else {

      store.dispatch(types.HIDE_LOADING_MSG);
      store.dispatch(types.CHANGE_MPGDIALOG_OPTS, {
        iconType: "warn",
        content: "结算失败",
        btnContent: "重新结算",
        btnFn: function() {
          wechatPay(store, data)
        },
        show: true
      })
    }
  }, response => {
    store.dispatch(types.HIDE_LOADING_MSG);
    store.dispatch(types.CHANGE_MPGDIALOG_OPTS, {
      iconType: "warn",
      content: "结算失败",
      btnContent: "重新结算",
      btnFn: function() {
        wechatPay(store, data)
      },
      show: true
    })
  })

}


export const setStateApp = (store, data) => {
  store.dispatch(types.SET_STATE_APP, data);
}

export const getOpenid = (store, data) => {
  store.dispatch(types.SET_WECHAT_OPENID, data);
}

export const refundOrder = ({
  dispatch, router, state
}, order) => {
  dispatch(types.CHANGE_MPGDIALOG_OPTS, {
    show: true,
    content: "正在退款",
    btnContent: "",
    iconType: "waiting"
  })
  api.refundOrder(order).then(
    response => {
      const result = response.data;
      if (+result.code == 200) {
        dispatch(types.CHANGE_MPGDIALOG_OPTS, {
          iconType: "success",
          content: "退款成功"
        })
        const timer = setTimeout(function() {
          dispatch(types.CHANGE_MPGDIALOG_OPTS, {
            show: false
          })
          clearTimeout(timer);
        }, 2000)
        order.processStatus.addDetailRefundSuccess()
      } else if (+result.code == 201) {
        //消息通知成功，已经到pos，此时返回201
        dispatch(types.CHANGE_MPGDIALOG_OPTS, {
          iconType: "",
          content: "已经通知成功，无需申请退款"
        })
        const timer = setTimeout(function() {
          dispatch(types.CHANGE_MPGDIALOG_OPTS, {
            show: false
          })
          clearTimeout(timer);
        }, 2000)
        order.processStatus.replaceDetail(result.data.processStatus
          .detail
          .pop());
      } else if (+result.code == 202) {
        //订单已经退款了，此时返回202
        dispatch(types.CHANGE_MPGDIALOG_OPTS, {
          iconType: "",
          content: "订单已退款"
        })
        const timer = setTimeout(function() {
          dispatch(types.CHANGE_MPGDIALOG_OPTS, {
            show: false
          })
          clearTimeout(timer);
        }, 2000)
        order.processStatus.replaceDetail(result.data.processStatus
          .detail
          .pop());
      } else {
        dispatch(types.CHANGE_MPGDIALOG_OPTS, {
          iconType: "warn",
          content: "退款失败",
          btnContent: "申请退款",
          btnFn: function() {
            refundOrder({
              dispatch, router, state
            }, order)
          }
        })
      }
    }, response => {
      dispatch(types.CHANGE_MPGDIALOG_OPTS, {
        iconType: "warn",
        content: "退款失败",
        btnContent: "申请退款",
        btnFn: function() {
          refundOrder({
            dispatch, router, state
          }, order)
        }
      })
    })
}

export const changeMpjDialogOptions = ({
  dispatch, router, state
}, options) => {
  dispatch(types.CHANGE_MPGDIALOG_OPTS, options);
  if (options.autoCancel) {
    setTimeout(function() {
      dispatch(types.CHANGE_MPGDIALOG_OPTS, {
        show: false
      })
    }, options.autoCancel)
  }
}



export const changeLoadingOptions = ({
  dispatch, router, state
}, options) => {
  if (options.show) {
    dispatch(types.SHOW_LOADING_MSG, options.content)
  } else {
    dispatch(types.HIDE_LOADING_MSG)
  }
}
